// ============================================================================
// Name : Closing.java
// Author : iron.yin@gmail.com
// Version : v1.0
// Copyright : RisingSun CO,.LTD
// Description : Closing.java in Java
// ============================================================================
package cc.risingsun.wing.core.util;

import java.io.IOException;
import java.io.InputStream;

/**
 * 用于关闭{@link InputStream}的辅助类
 * 
 * @author iron.yin@gmail.com
 */
public class Closing {

	/**
	 * 闭包
	 * @author iron.yin@gmail.com
	 */
	public static interface Closure {
		void fun(InputStream input) throws IOException;
	}

	public static Closing with(final InputStream input) {
		return new Closing(input);
	}

	private final InputStream input;

	public Closing(InputStream input) {
		this.input = input;
	}

	public void invoke(final Closure c) throws IOException {
		if (input == null)
			return;
		try {
			c.fun(input);
		} finally {
			try {
				input.close();
			} catch (IOException e) {
				throw e;
			}
		}
	}

}
